/**
 * Created by liuqingxia on 2016/4/11.
 */

var count = 0;//进度条计数器
var intervalId;//循环方法Id
var progressId = "#progressBar";
var progressBarDivId = "#progressBarDiv";

var isBack = 1;//是否有备库


$(document).ready(function () {
    var allDataSourceDiv = getAllDataSourceDiv("allDataSource-div", "/datasource/findAll", "master");
    allDataSourceDiv.init();

    var allBackUpDataSourceDiv = getAllDataSourceDiv("allBackUpDataSource-div", "/datasource/findAll", "slave");
    allBackUpDataSourceDiv.init();

    clickSourceInsertBtn("selectedDataSource-div", "master");
    clickSourceInsertBtn("backUpSelectedDataSource-div", "slave");

    clickSourceRemoveBtn();

    clickUseBackUpSourceBtn();

    clickCreateTableRadio();

    clickAppInsertCommitBtn();
    
    clickappAttrBtnEvent();
});

function clickUseBackUpSourceBtn() {
    $(document).on("click", "input[name='hasBackUp']", function () {
        var value = parseInt($(this).val());
        isBack = value;
        if (value == 1) {
            $("#backUpSourceDiv").show();
        }
        if (value == 0) {
            $("#backUpSourceDiv").hide();
        }
    });
}

/**
 * 进度条滚动...
 */
function progressing() {
    count = count + 1;
    if (count > 100) {
        window.clearInterval(intervalId);
        count = 0;
        return;
    }
    $(progressId).css("width", count + "%");
}

/**
 * 进度条滚动
 */
function setIntervalProgressBar() {
    intervalId = self.setInterval("progressing()", 100);
}

/**
 * 进度条显示
 */
function showProgressBar() {
    $(progressBarDivId).show();
}

/**
 * 隐藏进度条
 */
function hideProgressBar() {
    $(progressBarDivId).hide();
}

/**
 * 清空进度条
 */
function clearProgressBar() {
    window.clearInterval(intervalId);
    $(progressId).css("width", "0%");
}

/**
 * 完成进度条
 */
function fullProgressBar() {
    window.clearInterval(intervalId);
    count = 0;
    $(progressId).css("width", "100%");
}

var createTable = 0;

/**
 * 点击是否建表radio
 */
function clickCreateTableRadio() {
    $(document).on("click", "input[name='isCreateTable']", function () {
        var value = parseInt($(this).val());
        createTable = value;
        if (value == 1) {
            $("#shardSqlDiv").show();
        }
        if (value == 0) {
            $("#shardSqlDiv").hide();
        }
    });
}


/**
 * 点击AppInsert的提交按钮
 */
function clickAppInsertCommitBtn() {
    $(document).on("click", "#appInsertCommit-btn", function () {
    	
        var url = getUrlBySuffix("/tddl/app/createGddlShardApp");
        var params = newAssembleGddlShardApp();

        

        showProgressBar();
        setIntervalProgressBar();

        // console.log(JSON.stringify(params));

        $.postHttp(params, url, function (json) {
            if (json && json.success) {
                fullProgressBar();
                swal("成功", json['message'], "success");
            } else {
                swal("警告", json['message'], "error");
            }
            hideProgressBar();
            clearProgressBar();
        });

    });
}
/**
 * 获取gddlShardApp liyuefeng20161115
 * @returns {{}}
 */
function newAssembleGddlShardApp(){
	var gddlShardApp = getFormInputParams("appInsert-form");
    gddlShardApp["shardDbs"] = getShardDbs();
    gddlShardApp["shardDbTbSameName"] = getShardDbTbSameName();
    gddlShardApp["shardAlgorithm"] = getShardAlgorithm();
    gddlShardApp["shardOrder"] = getShardOrder();
    gddlShardApp['isCreateTable'] = createTable;
    gddlShardApp['isBack'] = isBack;
    gddlShardApp['appJsonArrayList']=getNewAppJsonArrayList();
    gddlShardApp['backDbs'] = getBackDbs();
    return gddlShardApp;
}
/**
 * 获取gddlShardApp
 * @returns {{}}
 */
function assembleGddlShardApp() {
    var gddlShardApp = getFormInputParams("appInsert-form");
    gddlShardApp["shardDbs"] = getShardDbs();
    gddlShardApp["shardDbTbSameName"] = getShardDbTbSameName();
    gddlShardApp["shardAlgorithm"] = getShardAlgorithm();
    gddlShardApp["shardOrder"] = getShardOrder();
    gddlShardApp['isCreateTable'] = createTable;
    gddlShardApp['isBack'] = isBack;

    gddlShardApp['backDbs'] = getBackDbs();
    return gddlShardApp;
}

function getBackDbs() {
    var shardDbs = [];
    $.each($("#backUpSelectedDataSource-div").find("span.dataSourceId"), function () {
        var dataSourceId = $(this).html();
        shardDbs.push($.trim(dataSourceId));
    });
    return shardDbs.join(",");
}

/**
 * 获取shardDbs
 * @returns {string}
 */
function getShardDbs() {
    var shardDbs = [];
    $.each($("#selectedDataSource-div").find("span.dataSourceId"), function () {
        var dataSourceId = $(this).html();
        shardDbs.push($.trim(dataSourceId));
    });
    return shardDbs.join(",");
}

/**
 * 获取shardDbTbSameName
 * @returns {string|*}
 */
function getShardDbTbSameName() {
    var shardDbTbSameName = $.trim($("#shardDbTbSameName").val());
    return shardDbTbSameName;
}

/**
 * 获取shardAlgorithm
 * @returns {string|*}
 */
function getShardAlgorithm() {
    var shardAlgorithm = $.trim($("#shardAlgorithm").val());
    return shardAlgorithm;
}

/**
 * 获取shardAlgorithm
 * @returns {string|*}
 */
function getShardOrder() {
    var shardOrder = $.trim($("#shardOrder").val());
    return shardOrder;
}
//生成分表属性添加模块
function getTddlAttrList(){
	var _html="<tr><td class='removeAttr'></td>";
	//物理表前缀
	var physicalTablePrefixHtml="<td><input type='text' class='form-control' name='physicsTbPrefix' placeholder='物理表前缀'></td>";
	//逻辑表名
	var logicalTableNameHtml="<td><input type='text' class='form-control' name='logicTbName' placeholder='逻辑表名'></td>";
	//分表字段
	var fieldHtml="<td><input type='text' class='form-control' name='shardTbFild' placeholder='分表字段'></td>";
    //分表数量
	var splitTableNum="<td><input type='number' min='2' class='form-control' name='shardTbCount' value='2'></td>";
	//分库数量
	var splitDataNum="<td><input type='number' min='1' class='form-control' name='shardDbCount' value='1'></td>";
	//后缀长度
	var suffixLength="<td><input type='number' min='0' class='form-control' name='suffixLength' value='0'></td>";
	//分库表名是否相同
	var isSameSTableName="<td><select class='selectpicker shardDbTbSameName' data-width= 'auto'><option selected value='1'>相同</option><option value='0'>不相同</option></select></td>";
	//分库分表算法
	var spliTableAlgorithm="<td><select class='selectpicker shardAlgorithm' data-width= 'auto'><option selected value='0'>哈希</option><option value='1'>取模</option></select></td>";
	//分表顺序
	var tableSequence = "<td><select class='selectpicker shardOrder' data-width= 'auto'><option selected value='0'>随机</option><option value='1'>顺序</option></select></td>";
	
	_html=_html+physicalTablePrefixHtml+logicalTableNameHtml+fieldHtml+splitTableNum+splitDataNum+suffixLength+isSameSTableName+spliTableAlgorithm+tableSequence+"</tr>";
	
	$("#insertTddlForm").find("table tbody").append(_html);
	
	$("#insertTddlForm").find(".shardDbTbSameName").selectpicker('refresh');
	$("#insertTddlForm").find(".shardAlgorithm").selectpicker('refresh');
	$("#insertTddlForm").find(".shardOrder").selectpicker('refresh');
	
}
function clickappAttrBtnEvent(){
	$(document).on("click","#appAttrBtn",function(){
		getTddlAttrList();
		$("#tddl-app-attr-modal").modal("show");
		clickRemoveAttrEvent();
		clickModalEvent();
		getFormValueToResult();
	})
	$(document).on("click","#appAttrBtnOnce",function(){
		getTddlAttrList();
		clickRemoveAttrEvent();
	})
}

function clickRemoveAttrEvent(){
	$(document).on("click",".removeAttr",function(){
		var thisTr=$(this).parent("tr");
		$(thisTr).remove();
	})
}
function clickModalEvent(){
	$("#tddl-app-attr-modal").find(".close").on("click",function(){
		$("#tddl-app-attr-modal").modal("hide");
	})
}

//收集属性数据，变为json串
function getAttrMessageToJson(){
	$("#insertTddlForm").find("#commitfuncDBtn").on("click",function(){
		var attrJsonArray="[";
		var dataTableTr=$("#insertTddlForm").find("table tbody tr");
		for(var i=0;i<dataTableTr.length;i++){
			var tempDataTableTr=dataTableTr[i];
			var physicsTbPrefix=$(tempDataTableTr).find("input[name=physicsTbPrefix]").val();
			var logicTbName=$(tempDataTableTr).find("input[name=logicTbName]").val();
			var shardTbFild=$(tempDataTableTr).find("input[name=shardTbFild]").val();
			var shardTbCount=$(tempDataTableTr).find("input[name=shardTbCount]").val();
			var shardDbCount=$(tempDataTableTr).find("input[name=shardDbCount]").val();
			var suffixLength=$(tempDataTableTr).find("input[name=suffixLength]").val();
			var shardDbTbSameName=$(tempDataTableTr).find(".shardDbTbSameName option:selected").val();
			var shardAlgorithm=$(tempDataTableTr).find(".shardAlgorithm option:selected").val();
			var shardOrder=$(tempDataTableTr).find(".shardOrder option:selected").val();
			
			if(""==physicsTbPrefix){
				swal("提示","物理表前缀不能为空");
				return false;
			}
			if(""==logicTbName){
				swal("提示","逻辑表名不能为空");
				return false;
			}
			if(""==shardTbFild){
				swal("提示","分表字段不能为空");
				return false;
			}
			var _tempValue="{'physicsTbPrefix':'"+$(tempDataTableTr).find("input[name=physicsTbPrefix]").val()+"','logicTbName':'"+$(tempDataTableTr).find("input[name=logicTbName]").val()+"','shardTbFild':'"+$(tempDataTableTr).find("input[name=shardTbFild]").val()+"','shardTbCount':'"+$(tempDataTableTr).find("input[name=shardTbCount]").val()+"','shardDbCount':'"+$(tempDataTableTr).find("input[name=shardDbCount]").val()+"','suffixLength':'"+$(tempDataTableTr).find("input[name=suffixLength]").val()+"','shardDbTbSameName':'"+$(tempDataTableTr).find(".shardDbTbSameName option:selected").val()+"','shardAlgorithm':'"+$(tempDataTableTr).find(".shardAlgorithm option:selected").val()+"','shardOrder':'"+$(tempDataTableTr).find(".shardOrder option:selected").val()+"'},"
			attrJsonArray+=_tempValue;
			
		}
		attrJsonArray=attrJsonArray.substring(0,attrJsonArray.lastIndexOf(","));
		attrJsonArray+="]";
		var re = new RegExp("\'", "g");
		attrJsonArray=attrJsonArray.replace(re,"\"");
		$("input[name=appJsonArrayList]").val(attrJsonArray);
		$("#tddl-app-attr-modal").modal("hide");
	})
}

function getFormValueToResult(){
	$("#insertTddlForm").find("#commitfuncDBtn").on("click",function(){
		var dataTableTr=$("#insertTddlForm").find("table tbody tr");
		var _html="";
		for(var i=0;i<dataTableTr.length;i++){
			var tempDataTableTr=dataTableTr[i];
			var physicsTbPrefix=$(tempDataTableTr).find("input[name=physicsTbPrefix]").val();
			var logicTbName=$(tempDataTableTr).find("input[name=logicTbName]").val();
			var shardTbFild=$(tempDataTableTr).find("input[name=shardTbFild]").val();
			var shardTbCount=$(tempDataTableTr).find("input[name=shardTbCount]").val();
			var shardDbCount=$(tempDataTableTr).find("input[name=shardDbCount]").val();
			var suffixLength=$(tempDataTableTr).find("input[name=suffixLength]").val();
			var shardDbTbSameName=$(tempDataTableTr).find(".shardDbTbSameName option:selected").val();
			var shardAlgorithm=$(tempDataTableTr).find(".shardAlgorithm option:selected").val();
			var shardOrder=$(tempDataTableTr).find(".shardOrder option:selected").val();
			
			if(""==physicsTbPrefix){
				swal("提示","物理表前缀不能为空");
				return false;
			}
			if(""==logicTbName){
				swal("提示","逻辑表名不能为空");
				return false;
			}
			if(""==shardTbFild){
				swal("提示","分表字段不能为空");
				return false;
			}
			var _trHtml="<tr><td class='removeAttr'></td>" +
					"<td class='physicsTbPrefix' value='"+physicsTbPrefix+"'>"+physicsTbPrefix+"</td>" +
					"<td class='logicTbName' value='"+logicTbName+"'>"+logicTbName+"</td>" +
					"<td class='shardTbFild' value='"+shardTbFild+"'>"+shardTbFild+"</td>" +
					"<td class='shardTbCount' value='"+shardTbCount+"'>"+shardTbCount+"</td>" +
					"<td class='shardDbCount' value='"+shardDbCount+"'>"+shardDbCount+"</td>" +
					"<td class='suffixLength' value='"+suffixLength+"'>"+suffixLength+"</td>" +
					"<td class='shardDbTbSameName' value='"+shardDbTbSameName+"'>"+(shardDbTbSameName=="1"?"相同":"不相同")+"</td>" +
					"<td class='shardAlgorithm' value='"+shardAlgorithm+"'>"+(shardAlgorithm=="0"?"哈希":"取模")+"</td>" +
					"<td class='shardOrder' value='"+shardOrder+"'>"+(shardOrder=="0"?"随机":"顺序")+"</td></tr>";
			
			_html+=_trHtml;
		}
		$("#insertTddlFormResult").find("tbody").html(_html);
		$(".tddl-matrix").show();
		$("#tddl-app-attr-modal").modal("hide");
	})
	clickRemoveAttrEvent();
}
function getNewAppJsonArrayList(){
	var attrJsonArray="[";
	var dataTableTr=$("#insertTddlFormResult").find("tbody tr");
	for(var i=0;i<dataTableTr.length;i++){
		var tempDataTableTr=dataTableTr[i];
		var physicsTbPrefix=$(tempDataTableTr).find(".physicsTbPrefix").attr("value");
		var logicTbName=$(tempDataTableTr).find(".logicTbName").attr("value");
		var shardTbFild=$(tempDataTableTr).find(".shardTbFild").attr("value");
		var shardTbCount=$(tempDataTableTr).find(".shardTbCount").attr("value");
		var shardDbCount=$(tempDataTableTr).find(".shardDbCount").attr("value");
		var suffixLength=$(tempDataTableTr).find(".suffixLength").attr("value");
		var shardDbTbSameName=$(tempDataTableTr).find(".shardDbTbSameName").attr("value");
		var shardAlgorithm=$(tempDataTableTr).find(".shardAlgorithm").attr("value");
		var shardOrder=$(tempDataTableTr).find(".shardOrder").attr("value");
		var _tempValue="{'physicsTbPrefix':'"+physicsTbPrefix+"','logicTbName':'"+logicTbName+"','shardTbFild':'"+shardTbFild+"','shardTbCount':'"+shardTbCount+"','shardDbCount':'"+shardDbCount+"','suffixLength':'"+suffixLength+"','shardDbTbSameName':'"+shardDbTbSameName+"','shardAlgorithm':'"+shardAlgorithm+"','shardOrder':'"+shardOrder+"'},"
		attrJsonArray+=_tempValue;
		
	}
	attrJsonArray=attrJsonArray.substring(0,attrJsonArray.lastIndexOf(","));
	attrJsonArray+="]";
	var re = new RegExp("\'", "g");
	attrJsonArray=attrJsonArray.replace(re,"\"");
	return attrJsonArray;
}